//
// Created by Administrator on 2023/6/4.
//
#pragma once
#ifndef SCATTER_PLOT_H
#define SCATTER_PLOT_H

#include <QWidget>
#include <QPaintEvent>
#include <QPainter>


class ScatterPlotWidget : public QWidget
{
public:
    ScatterPlotWidget(QWidget *parent = nullptr) : QWidget(parent)
    {
        // 示例数据
        points << QPointF(10, 20)
               << QPointF(30, 40)
               << QPointF(50, 60)
               << QPointF(70, 80)
               << QPointF(90, 100);
    }

protected:
    void paintEvent(QPaintEvent *event) override
    {
        Q_UNUSED(event);

        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.fillRect(rect(), Qt::white);

        // 设置坐标系范围
        double minX = 0;
        double maxX = 100;
        double minY = 0;
        double maxY = 100;

        // 绘制坐标系
        painter.setPen(Qt::black);
        painter.drawLine(margin, height() - margin, margin, margin); // y轴
        painter.drawLine(margin, height() - margin, width() - margin, height() - margin); // x轴

        // 绘制坐标轴数据
        painter.setPen(Qt::blue);
        painter.setFont(QFont("Arial", 10));
        painter.drawText(QRectF(margin, height() - margin, width() - 2 * margin, margin), Qt::AlignCenter, QString::number(minX));
        painter.drawText(QRectF(width() - margin, height() - margin, margin, margin), Qt::AlignCenter, QString::number(maxX));
        painter.drawText(QRectF(0, margin, margin, height() - 2 * margin), Qt::AlignCenter, QString::number(maxY));
        painter.drawText(QRectF(0, 0, margin, margin), Qt::AlignCenter, QString::number(minY));

        // 计算每个数据点在绘图区域中的坐标
        QVector<QPointF> plotPoints;
        for (const QPointF &point : points) {
            double x = margin + (point.x() - minX) / (maxX - minX) * (width() - 2 * margin);
            double y = height() - margin - (point.y() - minY) / (maxY - minY) * (height() - 2 * margin);
            plotPoints.append(QPointF(x, y));
        }

        // 绘制散点图数据点
        painter.setPen(Qt::red);
        painter.setBrush(Qt::red);
        for (const QPointF &point : plotPoints) {
            painter.drawEllipse(point, 5, 5);
        }
    }

private:
    QVector<QPointF> points;
    const int margin = 50;
};





#endif //SCATTER_PLOT_H
